
const Service = require('egg').Service;

class BMService extends Service {
  constructor() {
    super(...arguments);
    /**
     *@abstract 初始化连接的数据库 db1
    */
    this.client1 = this.app.mysql.get('db1');
  }
  /**
	* @param param 报名参数
	*/
  async send(param) {
    const { ctx } = this;
    const {
      name,
      phone,
      carSeriesCode,
      dealer,
      public_key,
      private_key,
      autohome_sale_name,
      clueType,
      source_pkid,
    } = param;
    const timestamp = Date.now();
    /**
     * 重组数据结构
    */
    const body = {
      request: {
        body: {
          list: [
            {
              name,
              mobile: phone,
              carSeriesCode,
              dealer_code: dealer,
              autohome_sale_name,
              clueType,
            },
          ],
          source_pkid,
        },
        head: {
          public_key,
          secret_key: ctx.helper.md5([ public_key, private_key, timestamp ].join(''), true),
          timestamp,
        },
      },
    };
    /**
     * 调用第三方接口
    */
    try {
      const result = await ctx.curl('http://api.ddp.fawbenteng.ecs.cedarmg.com/postclue/postclue', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        dataType: 'json',
        data: body,
      });
      const insertData = {
        name,
        phone,
        carSeriesCode,
        dealer_id: dealer,
        public_key,
        private_key,
        autohome_sale_name,
        clueType,
        source_pkid,
        content: JSON.stringify(result.data),
        createtime: timestamp,
      };
      const { createDb } = ctx.helper;
      const insertDb = await createDb(this.client1, 'tx_signupbenteng', insertData);
      if (insertDb.affectedRows === 1) {
        ctx.getLogger('bmLogger').info('bm success', insertData);
        return {
          code: 200,
          message: 'success',
          data: insertData,
        };
      }
      return {
        code: 500,
        message: '报名失败',
      };
    } catch (error) {
      throw new Error(`报名失败:${error}`);
    }
  }
}


module.exports = BMService;
